﻿using System;
using System.Windows.Forms;
using PersonMgrApp.Interfaces;

namespace PersonMgrApp
{
    public partial class PersonMgrForm : Form
    {
        private readonly IDataAccessLayer _dataAccessLayer;
        private readonly IPersonMgr _personMgr;

        public PersonMgrForm(IDataAccessLayer dataAccessLayer, IPersonMgr personMgr)
        {
            _dataAccessLayer = dataAccessLayer;
            _personMgr = personMgr;

            InitializeComponent();
            RefreshNameList();
        }

        private void RefreshNameList()
        {
            PersonListView.Items.Clear();

            var personAges = _dataAccessLayer.GetPersonAges();
            foreach (var person in personAges)
            {
                var newItem = new ListViewItem(person.Key);
                newItem.SubItems.Add(person.Value.ToString());

                PersonListView.Items.Add(newItem);
            }
        }

        private void AddPersonButtonClick(object sender, EventArgs e)
        {
            int age;
            if (String.IsNullOrWhiteSpace(NameTextBox.Text) || !Int32.TryParse(AgeTextBox.Text, out age))
            {
                MessageBox.Show("Make sure that name is valid, and age is a number", "Invalid Entry",
                                MessageBoxButtons.OK);
                return;
            }

            _dataAccessLayer.UpsertPerson(NameTextBox.Text, age);
            RefreshNameList();
        }

        private void LookupAgeButtonClick(object sender, EventArgs e)
        {
            if(string.IsNullOrEmpty(LookupNameTextBox.Text))
            {
                MessageBox.Show("Enter a valid name to lookup the persons age", "Invalid Entry",
                                MessageBoxButtons.OK);
                return;
            }

            var age = _personMgr.GetPersonAge(LookupNameTextBox.Text);
            MessageBox.Show(LookupNameTextBox.Text + ": " + age.ToString(), "Returned Age", MessageBoxButtons.OK);
        }
    }
}
